package com.bupt.smart.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.bupt.smart.application.CustomApplication;
import com.bupt.smart.model.RepairRequest;
import com.bupt.smart.network.APIManager;
import com.bupt.smart.smart.R;
import com.bupt.smart.ui.adapter.PhotoRecyclerViewAdapter;
import com.bupt.smart.ui.widget.RecordButton;
import com.bupt.smart.utils.AudioRecorder;
import com.bupt.smart.utils.Constants;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.yongchun.library.view.ImageSelectorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cc.cloudist.acplibrary.ACProgressConstant;
import cc.cloudist.acplibrary.ACProgressFlower;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class NewRepairActivity extends AppCompatActivity {
    @BindView(R.id.title)
    EditText title;
    @BindView(R.id.content)
    EditText content;
    @BindView(R.id.photo_recycler_view)
    RecyclerView photoRecyclerView;
    @BindView(R.id.submit_repair)
    Button submitButton;
    @BindView(R.id.btn_record)
    RecordButton recordButton;

    private ACProgressFlower dialog;
    private AudioRecorder audioRecorder;

    private String audioPath = null;
    private ArrayList<String> imagePath = new ArrayList<>();
    private ArrayList<String> imageUrls = new ArrayList<>();
    private String audioUrl = null;

    private UploadManager uploadManager = null;
    private String uploadToken = null;

    private PhotoRecyclerViewAdapter photoRecyclerViewAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_repair);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        photoRecyclerViewAdapter = new PhotoRecyclerViewAdapter(this, imagePath);
        photoRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        photoRecyclerView.setAdapter(photoRecyclerViewAdapter);
        audioRecorder = new AudioRecorder();
        recordButton.setAudioRecord(audioRecorder);
        dialog = new ACProgressFlower.Builder(this)
                .direction(ACProgressConstant.DIRECT_CLOCKWISE)
                .themeColor(Color.WHITE)
                .text("提交中")
                .fadeColor(Color.DKGRAY).build();
        uploadManager = new UploadManager();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_new_repair, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @OnClick(R.id.submit_repair)
    public void submitRepair() {
        dialog.show();
        Call<Map<String, String>> call = APIManager.getQiNiuCloudAPI().getUploadToken();
        call.enqueue(new Callback<Map<String, String>>() {
            @Override
            public void onResponse(Call<Map<String, String>> call, Response<Map<String, String>> response) {
                if (response.isSuccessful() && response.body().get("uploadToken") != null) {
                    uploadToken = response.body().get("uploadToken");
                    uploadImages();
                } else {
                    dialog.dismiss();
                    Toast.makeText(NewRepairActivity.this, getString(R.string.get_upload_token_failed), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Map<String, String>> call, Throwable t) {
                dialog.dismiss();
                Toast.makeText(NewRepairActivity.this, getString(R.string.get_upload_token_failed), Toast.LENGTH_SHORT).show();
                t.printStackTrace();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == ImageSelectorActivity.REQUEST_IMAGE){
            ArrayList<String> images = (ArrayList<String>) data.getSerializableExtra(ImageSelectorActivity.REQUEST_OUTPUT);
            imagePath.addAll(images);
            photoRecyclerViewAdapter.notifyDataSetChanged();
        }
    }

    private void uploadImages() {
        if (imagePath.size() == 0) {
            uploadAudio();
        } else {
            for (String path : imagePath) {
                uploadManager.put(path, null, uploadToken, new UpCompletionHandler() {
                    @Override
                    public void complete(String s, ResponseInfo responseInfo, JSONObject jsonObject) {
                        String key = null;
                        try {
                            key = jsonObject.getString("key");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        System.out.println("image key: " + key);
                        imageUrls.add(Constants.QINIU_URL + key);
                        if (imagePath.size() == imageUrls.size()) {
                            uploadAudio();
                        }
                    }
                }, null);
            }
        }
    }

    private void uploadAudio() {
        audioPath = audioRecorder.getFilePath();
        if (audioPath == null) {
            uploadRepairRequest();
        } else {
            uploadManager.put(audioPath, null, uploadToken, new UpCompletionHandler() {
                @Override
                public void complete(String s, ResponseInfo responseInfo, JSONObject jsonObject) {
                    String key = null;
                    try {
                        key = jsonObject.getString("key");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    System.out.println("audio key: " + key);
                    audioUrl = Constants.QINIU_URL + key;
                    uploadRepairRequest();
                }
            }, null);
        }
    }

    private void uploadRepairRequest() {
        RepairRequest repairRequest = new RepairRequest();
        repairRequest.setUserID(((CustomApplication) getApplication()).getUserInfo().getUserID());
        repairRequest.setTitle(title.getText().toString());
        repairRequest.setContent(content.getText().toString());
        repairRequest.setImages(imageUrls);
        repairRequest.setAudio(audioUrl);
        repairRequest.setDate(new Timestamp(System.currentTimeMillis()));
        repairRequest.setStatus(Constants.UNHANDLED);

        Call<Map<String, Boolean>> call = APIManager.getRepairAPI().submitRepairRequest(((CustomApplication) getApplication()).getUserInfo().getUserID(),
                repairRequest);

        call.enqueue(new Callback<Map<String, Boolean>>() {
            @Override
            public void onResponse(Call<Map<String, Boolean>> call, Response<Map<String, Boolean>> response) {
                dialog.dismiss();
                if (response.body().get("result") == true) {
                    Toast.makeText(NewRepairActivity.this, getString(R.string.submit_repair_succeed), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(NewRepairActivity.this, getString(R.string.submit_repair_failed), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Map<String, Boolean>> call, Throwable t) {
                dialog.dismiss();
                t.printStackTrace();
                Toast.makeText(NewRepairActivity.this, getString(R.string.submit_repair_failed), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
